<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="竞赛" prop="competitionId">
        <el-select v-model="queryParams.competitionId" placeholder="请选择竞赛" clearable style="width: 200px">
          <el-option
            v-for="competition in competitionList"
            :key="competition.id"
            :label="competition.name"
            :value="competition.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="奖项等级" prop="awardLevel">
        <el-select v-model="queryParams.awardLevel" placeholder="请选择奖项等级" clearable style="width: 150px">
          <el-option label="一等奖" value="一等奖" />
          <el-option label="二等奖" value="二等奖" />
          <el-option label="三等奖" value="三等奖" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['race:win:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['race:win:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['race:win:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['race:win:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="winList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="获奖ID" align="center" prop="id" />
      <el-table-column label="竞赛名称" align="center" prop="competitionName" />
      <el-table-column label="参赛者" align="center" prop="participantName" />
      <el-table-column label="成果物名称" align="center" prop="resultName" />
      <el-table-column label="奖项等级" align="center" prop="awardLevel">
        <template #default="scope">
          <el-tag v-if="scope.row.awardLevel === '一等奖'" type="danger">{{ scope.row.awardLevel }}</el-tag>
          <el-tag v-else-if="scope.row.awardLevel === '二等奖'" type="warning">{{ scope.row.awardLevel }}</el-tag>
          <el-tag v-else-if="scope.row.awardLevel === '三等奖'" type="success">{{ scope.row.awardLevel }}</el-tag>
          <el-tag v-else>{{ scope.row.awardLevel }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="获奖时间" align="center" prop="awardTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.awardTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="获奖原因" align="center" prop="awardReason" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button size="small" type="text" icon="View" @click="handleDetail(scope.row)" v-hasPermi="['race:win:query']">详情</el-button>
          <el-button size="small" type="text" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['race:win:edit']">修改</el-button>
          <el-button size="small" type="text" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['race:win:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改竞赛获奖管理对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="竞赛" prop="competitionId">
          <el-select v-model="form.competitionId" placeholder="请选择竞赛" @change="handleCompetitionChange" style="width: 100%">
            <el-option
              v-for="competition in competitionList"
              :key="competition.id"
              :label="competition.name"
              :value="competition.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="报名记录" prop="signupId">
          <el-select v-model="form.signupId" placeholder="请选择报名记录" @change="handleSignupChange" style="width: 100%">
            <el-option
              v-for="signup in signupList"
              :key="signup.id"
              :label="`${signup.participantName} - ${signup.contactPhone}`"
              :value="signup.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="成果物" prop="resultId">
          <el-input v-model="form.resultName" placeholder="自动获取成果物" disabled style="width: 100%" />
        </el-form-item>
        <el-form-item label="奖项等级" prop="awardLevel">
          <el-select v-model="form.awardLevel" placeholder="请选择奖项等级" style="width: 100%">
            <el-option label="一等奖" value="一等奖" />
            <el-option label="二等奖" value="二等奖" />
            <el-option label="三等奖" value="三等奖" />
          </el-select>
        </el-form-item>
        <el-form-item label="获奖时间" prop="awardTime">
          <el-date-picker
            v-model="form.awardTime"
            type="datetime"
            placeholder="请选择获奖时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="获奖原因" prop="awardReason">
          <el-input v-model="form.awardReason" type="textarea" :rows="3" placeholder="请输入获奖原因" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog title="获奖详情" v-model="detailOpen" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="获奖ID">{{ detailForm.id }}</el-descriptions-item>
        <el-descriptions-item label="竞赛名称">{{ detailForm.competitionName }}</el-descriptions-item>
        <el-descriptions-item label="参赛者">{{ detailForm.participantName }}</el-descriptions-item>
        <el-descriptions-item label="成果物名称">{{ detailForm.resultName }}</el-descriptions-item>
        <el-descriptions-item label="奖项等级">
          <el-tag v-if="detailForm.awardLevel === '一等奖'" type="danger">{{ detailForm.awardLevel }}</el-tag>
          <el-tag v-else-if="detailForm.awardLevel === '二等奖'" type="warning">{{ detailForm.awardLevel }}</el-tag>
          <el-tag v-else-if="detailForm.awardLevel === '三等奖'" type="success">{{ detailForm.awardLevel }}</el-tag>
          <el-tag v-else>{{ detailForm.awardLevel }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="获奖时间">{{ detailForm.awardTime ? parseTime(detailForm.awardTime) : '未设置' }}</el-descriptions-item>
        <el-descriptions-item label="获奖原因" :span="2">{{ detailForm.awardReason || '无' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailForm.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, getCurrentInstance } from 'vue'
import { listWin, getWin, addWin, updateWin, delWin } from '@/api/race/win'
import { listCompetition } from '@/api/race/competition'
import { listCompetitionSignup } from '@/api/race/competitionSignup'
import { listCompetitionResult } from '@/api/race/competitionResult'

const { proxy } = getCurrentInstance()

const winList = ref([])
const loading = ref(true)
const open = ref(false)
const detailOpen = ref(false)
const title = ref('')
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const competitionList = ref([])
const signupList = ref([])
const resultList = ref([])

const data = reactive({
  form: {},
  detailForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    competitionId: null,
    awardLevel: null
  },
  rules: {
    competitionId: [
      { required: true, message: "竞赛不能为空", trigger: "change" }
    ],
    signupId: [
      { required: true, message: "报名记录不能为空", trigger: "change" }
    ],
    resultId: [
      { required: true, message: "成果物不能为空", trigger: "change" }
    ],
    awardLevel: [
      { required: true, message: "奖项等级不能为空", trigger: "change" }
    ],
    awardTime: [
      { required: true, message: "获奖时间不能为空", trigger: "change" }
    ]
  }
})

const { queryParams, form, detailForm, rules } = toRefs(data)

/** 查询竞赛获奖管理列表 */
function getList() {
  loading.value = true
  listWin(queryParams.value).then(response => {
    winList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 查询竞赛列表 */
function getCompetitionList() {
  listCompetition({}).then(response => {
    // 过滤出已完赛的竞赛（状态为4）
    competitionList.value = response.rows.filter(competition => competition.competitionStatus === 4)
  })
}

/** 竞赛选择变化 */
function handleCompetitionChange(competitionId) {
  if (competitionId) {
    listCompetitionSignup({ competitionId: competitionId }).then(response => {
      signupList.value = response.rows
    })
  } else {
    signupList.value = []
    resultList.value = []
    form.value.signupId = null
    form.value.resultId = null
    form.value.resultName = null
  }
}

/** 报名记录选择变化 */
function handleSignupChange(signupId) {
  if (signupId && form.value.competitionId) {
    listCompetitionResult({ 
      competitionId: form.value.competitionId,
      signupId: signupId
    }).then(response => {
      resultList.value = response.rows
      // 自动选择第一个成果物（如果存在）
      if (response.rows && response.rows.length > 0) {
        form.value.resultId = response.rows[0].id
        form.value.resultName = response.rows[0].resultName
      } else {
        form.value.resultId = null
        form.value.resultName = null
      }
    })
  } else {
    resultList.value = []
    form.value.resultId = null
    form.value.resultName = null
  }
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    competitionId: null,
    signupId: null,
    resultId: null,
    resultName: null,
    awardLevel: null,
    awardTime: null,
    awardReason: null,
    remark: null
  }
  signupList.value = []
  resultList.value = []
  proxy.resetForm("formRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryForm")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加竞赛获奖管理"
  getCompetitionList()
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const id = row.id || ids.value
  getWin(id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改竞赛获奖管理"
    getCompetitionList()
    if (form.value.competitionId) {
      handleCompetitionChange(form.value.competitionId)
      if (form.value.signupId) {
        handleSignupChange(form.value.signupId)
      }
    }
  })
}

/** 详情按钮操作 */
function handleDetail(row) {
  getWin(row.id).then(response => {
    detailForm.value = response.data
    detailOpen.value = true
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["formRef"].validate(valid => {
    if (valid) {
      // 复制表单数据并转换日期格式
      const submitData = { ...form.value }
      if (submitData.awardTime) {
        // 将日期转换为 yyyy-MM-dd HH:mm:ss 格式
        const date = new Date(submitData.awardTime)
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        submitData.awardTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      }
      
      if (form.value.id != null) {
        updateWin(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addWin(submitData).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除竞赛获奖管理编号为"' + _ids + '"的数据项？').then(function() {
    return delWin(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('race/win/export', {
    ...queryParams.value
  }, `win_${new Date().getTime()}.xlsx`)
}

getList()
getCompetitionList()
</script>
